package com.paic.mhis.hcpms.audit.biz.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.paic.mhis.core.auth.biz.service.UserDetails;
import com.paic.mhis.hcpms.audit.biz.service.AuditProjectService;
import com.paic.mhis.hcpms.audit.biz.service.AuditWorkFlowService;
import com.paic.mhis.hcpms.audit.biz.service.ICaseCommonService;
import com.paic.mhis.hcpms.audit.constants.AuditConstants;
import com.paic.mhis.hcpms.audit.dao.AuditOpinionDao;
import com.paic.mhis.hcpms.audit.dao.AuditProjectDao;
import com.paic.mhis.hcpms.audit.dto.AuditCaseDTO;
import com.paic.mhis.hcpms.audit.dto.AuditNotificationDTO;
import com.paic.mhis.hcpms.audit.dto.AuditOpinionDTO;
import com.paic.mhis.hcpms.audit.dto.AuditProjectDTO;
import com.paic.mhis.hcpms.common.document.biz.service.IDocumentService;
import com.paic.mhis.hcpms.common.document.dto.DocContentDTO;
import com.paic.mhis.hcpms.common.document.dto.DocParameterCondition;
import com.paic.mhis.hcpms.common.document.dto.DocSaveParamterDTO;
import com.paic.mhis.hcpms.common.document.intergration.DocumentDao;
import com.paic.mhis.hcpms.common.document.util.Constant;
import com.paic.mhis.hcpms.common.storage.biz.service.impl.HcpmsStorageServiceImpl;
import com.paic.mhis.hcpms.common.storage.dto.HcpmsStorageDTO;
import com.paic.mhis.hcpms.trust.biz.service.IntegrityMedicalService;

/**
 * 
 * @author EX-LUORONG001
 * 
 */
@Component("auditProjectService")
public class AuditProjectServiceImpl implements AuditProjectService {
	@Autowired
	private AuditProjectDao auditProjectDao;

	@Autowired
	private AuditOpinionDao auditOpinionDao;

	@Autowired
	private DocumentDao documentDao;

	@Autowired
	private IDocumentService documentService;

	@Autowired
	private IntegrityMedicalService integrityMedicalService;

	@Autowired
	private AuditWorkFlowService auditWorkFlowService; // 流程服务

	@Autowired
	private HcpmsStorageServiceImpl hcpmsStorageService;// 暂存临时表

	@Autowired
	private ICaseCommonService commonService;

	public Map<String, Object> getCase(AuditCaseDTO caseDTO) {
		Map<String, Object> map = new HashMap<String, Object>();
		AuditCaseDTO caseDto = auditProjectDao
				.getAuditCaseDTOByProblemNo(caseDTO);

		map.put("case", caseDto);
		return map;
	}

	/**
	 * 1.更新案件状态为稽核待复核,保存初审稽核的意见 批量提交
	 * 
	 * @throws Exception
	 */
	@Transactional
	public Map<String, Object> updateBatchCase(UserDetails user,
			String[] caseCodes, Map<String, Object> map) throws Exception {
		int count = 0;
		HcpmsStorageDTO vo = new HcpmsStorageDTO();
		vo.setUserId(user.getUsername());
		vo.setModuleType(AuditConstants.jhModule);
		vo.setChildModuleType(AuditConstants.audit);
		vo.setBusinessType(AuditConstants.opinionType_11);

		AuditOpinionDTO opinionDTO = new AuditOpinionDTO();
		opinionDTO.setDealUserName(user.getUsername());
		opinionDTO.setOpinionType(AuditConstants.opinionType_11);
		opinionDTO.setOpinion("0");
		for (String caseCode : caseCodes) {
			vo.setBusinessId(caseCode);
			JSONObject transferJsons = (JSONObject) hcpmsStorageService
					.getStorageDataMap(vo);
			AuditCaseDTO auditCaseDTO = JSONObject.toJavaObject(transferJsons,
					AuditCaseDTO.class);
			if (null != auditCaseDTO) {
				JSONObject transferJson = commonService
						.queryBatchOpertionAuditCasePoint(caseCode,
								user.getUsername());// 获取临时扣分
				auditCaseDTO.setTempFlag("0");
				this.updateCase(auditCaseDTO, opinionDTO, user, transferJson,
						map);
				// 医务人员、参保人进行数据添加
				commonService.batchOpertionMedicalCommon(caseCode,
						AuditConstants.taskType_02, user.getUsername());
				count++;
			}
		}
		map.put("state", AuditConstants.FLAG_TURE);
		map.put("msg", "操作成功" + count + "条，失败" + (caseCodes.length - count)
				+ "条!");
		return map;
	}

	/**
	 * 1.更新案件状态为稽核待复核,保存初审稽核的意见
	 * 
	 * @throws Exception
	 */
	@Transactional
	public Map<String, Object> updateCase(AuditCaseDTO caseDTO,
			AuditOpinionDTO opinionDTO, UserDetails user,
			JSONObject transferJson, Map<String, Object> map) throws Exception {
		// onlySave：1，暂存；0，保存
		if (StringUtils.hasText(caseDTO.getTempFlag())
				&& "0".equals(caseDTO.getTempFlag())) {
			// 更新案件状态
			caseDTO.setCaseState(AuditConstants.auditCaseStatus_3);
			caseDTO.setTempFlag(AuditConstants.TEMP_FLAG_0);
			auditProjectDao.updateAuditCaseDTOByProblemNo(caseDTO);

			// 添加稽核项目
			this.addOrUpdateAuditProject(caseDTO.getProjectList(),
					caseDTO.getCaseCode());
			// 添加稽核告知函
			this.addAuditNotification(caseDTO.getNotificationDTO(),
					user.getUsername(), caseDTO, opinionDTO.getOpinion());

			// 保存意见
			opinionDTO.setTaskType(AuditConstants.taskType_02);
			Date date = new Date();
			SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");
			String dates = sft.format(date);
			opinionDTO.setDealDate(dates);
			opinionDTO.setIsDeleted(AuditConstants.isDeleted);
			opinionDTO.setOpinion(caseDTO.getOpinion());
			opinionDTO.setOpinionDesc(caseDTO.getOpinionDesc());
			opinionDTO.setProblemNo(caseDTO.getCaseCode());

			int counts = auditOpinionDao.getOpinionCount(opinionDTO);
			if (counts > 0) {
				auditOpinionDao.updateProblemOpinion(opinionDTO);
				map.put("state", AuditConstants.FLAG_TURE);
				map.put("msg", AuditConstants.UPDATE_SUCCESS);
			} else {
				auditOpinionDao.addOpinion(opinionDTO);
				map.put("state", AuditConstants.FLAG_TURE);
				map.put("msg", AuditConstants.INSERT_SUCCESS);
			}
			// 删除暂存信息：
			this.deleteStorageData(caseDTO.getCaseCode(),
					AuditConstants.jhModule, AuditConstants.audit,
					AuditConstants.opinionType_11, user.getUsername());

			// 扭转流程
			AuditOpinionDTO paramter = new AuditOpinionDTO();
			paramter.setOpinionType(AuditConstants.opinionType_10);
			paramter.setTaskType(AuditConstants.taskType_02);
			paramter.setProblemNo(caseDTO.getCaseCode());
			AuditOpinionDTO currentOpinionBean = this.auditOpinionDao
					.getOpinionByType(paramter);
			String secondUsername = currentOpinionBean.getAppointSecond();

			this.auditWorkFlowService.processWorkFlow(caseDTO.getCaseCode(),
					user, secondUsername.toUpperCase(), null,
					AuditConstants.TASK_TYPE_CASE);
		} else if (StringUtils.hasText(caseDTO.getTempFlag())
				&& "1".equals(caseDTO.getTempFlag())) {
			// 暂存（添加）
			this.saveStorageData(caseDTO.getCaseCode(),
					AuditConstants.jhModule, AuditConstants.audit,
					AuditConstants.opinionType_11, user.getUsername(), caseDTO,
					map);
		}
		// 扣分
		this.getAuditCasePoint(caseDTO, transferJson, user.getUsername());
		return map;
	}

	public String getDeductionAmmount(AuditProjectDTO caseDTO) {
		String ammount = auditProjectDao.getDeductionAmmount(caseDTO);
		if (null == ammount || "".equals(ammount)) {
			ammount = "0.00";
		}
		return ammount;
	}

	public Map<String, Object> getAuditProjectList(AuditProjectDTO projectDTO) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<AuditProjectDTO> auList = auditProjectDao
				.getAuditProjectList(projectDTO);
		map.put("auditProjectList", auList);

		return map;
	}

	public void addOrUpdateAuditProject(List<AuditProjectDTO> proList,
			String caseCode) {
		// 根据案件编号判断是否存在稽核项目
		int count = auditProjectDao.getCaseProjectCount(caseCode);
		if (count > 0) {
			AuditProjectDTO projectDTO = new AuditProjectDTO();
			projectDTO.setCaseCode(caseCode);
			projectDTO.setIsDeleted(AuditConstants.isDeleted_1);
			auditProjectDao.updateAuditProject(projectDTO);
		}
		if (null != proList && proList.size() > 0) {
			for (int i = 0; i < proList.size(); i++) {
				AuditProjectDTO projectDTO = proList.get(i);
				projectDTO.setIsDeleted(AuditConstants.isDeleted);
				projectDTO.setCaseCode(caseCode);
				auditProjectDao.insertAuditProject(projectDTO);
			}
		}
	}

	public Map<String, Object> getAuditNotification(
			AuditNotificationDTO notificationDTO, Map<String, Object> map) {
		AuditNotificationDTO auditNotificationDTO = auditProjectDao
				.getAuditNotifications(notificationDTO);

		// 以下初始化sealDate 和reginName;

		// /处理文档
		DocParameterCondition condition = new DocParameterCondition();
		condition.setDocType(Constant.docType_05);
		condition.setTaskType(Constant.taskType_05);
		condition.setTaskNo(notificationDTO.getCaseCode());

		List<DocContentDTO> list = this.documentService
				.queryByDocParameterCondition(condition);
		this.processDocumentNotification(auditNotificationDTO, list);
		map.put("state", AuditConstants.FLAG_TURE);
		map.put("result", auditNotificationDTO);
		return map;
	}

	private void processDocumentNotification(
			AuditNotificationDTO notificationBean, List<DocContentDTO> list) {
		for (DocContentDTO bean : list) {
			String docKey = bean.getDocKey();
			String docValue1 = bean.getDocValue1();

			if (AuditConstants.sealDate.equals(docKey)) {
				notificationBean.setSealDate(docValue1);
			} else if (AuditConstants.regionName.equals(docKey)) {
				notificationBean.setRegionName(docValue1);
			}
		}
	}

	public Map<String, Object> addAuditNotification(AuditNotificationDTO auDto,
			String userName, AuditCaseDTO caseDTO, String state) {
		Map<String, Object> map = new HashMap<String, Object>();
		DocSaveParamterDTO bean = new DocSaveParamterDTO();
		int count = auditProjectDao.getAuditNotification(caseDTO);
		map.put("caseCode", caseDTO.getCaseCode());

		if (null != auDto) {
			if (null != auDto.getHealthcareProviderName()
					&& !"".equals(auDto.getHealthcareProviderName())) {
				map.put("healthcareProviderName",
						auDto.getHealthcareProviderName());
			}
			if (null != auDto.getFullAddress()
					&& !"".equals(auDto.getFullAddress())) {
				map.put("fullAddress", auDto.getFullAddress());
			}
			if (null != auDto.getPointStartDate()
					&& !"".equals(auDto.getPointStartDate())) {
				map.put("pointStartDate", auDto.getPointStartDate());
			}
			if (null != auDto.getLealPerson()
					&& !"".equals(auDto.getLealPerson())) {
				map.put("lealPerson", auDto.getLealPerson());
			}
			map.put("auditDate", auDto.getAuditDate());
			map.put("periodBeginDate", auDto.getPeriodBeginDates());
			map.put("periodEndDate", auDto.getPeriodEndDates());
			map.put("auditSummary", auDto.getAuditSummary());
			map.put("opinionDesc", auDto.getOpinionDesc());
			map.put("sealDate", auDto.getSealDate());
			map.put("regionName", auDto.getRegionName());

			bean.setMap(map);
			bean.setCreateUser(userName);
			bean.setDocType(Constant.docType_05);
			bean.setTaskNo(auDto.getCaseCode());
			bean.setTaskType(Constant.taskType_05);
		}
		if (count > 0) {
			if ("0".equals(state))// 异常
			{
				documentService.updateDocContentDTO(bean);
			} else {
				caseDTO.setIsDeleted(AuditConstants.isDeleted_1);
				documentDao.updateDocument(caseDTO);
			}
		} else if (null != auDto) {
			documentService.saveDocumentContent(bean);
		}

		map.put("state", AuditConstants.FLAG_TURE);
		map.put("msg", AuditConstants.INSERT_SUCCESS);
		return map;
	}

	// 暂存
	public Map<String, Object> saveStorageData(String businessId,
			String moduleType, String childModuleType, String businessType,
			String userName, Object opinionDTO, Map<String, Object> map) {
		HcpmsStorageDTO vo = new HcpmsStorageDTO();
		vo.setBusinessId(businessId);
		vo.setModuleType(moduleType);
		vo.setChildModuleType(childModuleType);
		vo.setBusinessType(businessType);
		vo.setUserId(userName);
		vo.setDataMap(opinionDTO);
		hcpmsStorageService.saveStorageData(vo, false);
		map.put("state", AuditConstants.FLAG_TURE);
		map.put("msg", AuditConstants.ZCMSG);
		return map;
	}

	// 暂存删除
	public void deleteStorageData(String businessId, String moduleType,
			String childModuleType, String businessType, String userName) {
		HcpmsStorageDTO vo = new HcpmsStorageDTO();
		vo.setBusinessId(businessId);
		vo.setModuleType(moduleType);
		vo.setChildModuleType(childModuleType);
		vo.setBusinessType(businessType);
		vo.setUserId(userName);
		hcpmsStorageService.deleteStorageData(vo);
	}

	// 扣分
	public void getAuditCasePoint(AuditCaseDTO caseDTO,
			JSONObject transferJson, String userName) throws Exception {
		if (StringUtils.hasText(caseDTO.getTempFlag())
				&& "0".equals(caseDTO.getTempFlag())) {
			integrityMedicalService.addIntegrityPointTemps(transferJson,
					userName);// 临时扣分
			this.commonService.deleteAuditCasePoint(caseDTO.getCaseCode(),
					userName);

		} else if (StringUtils.hasText(caseDTO.getTempFlag())
				&& "1".equals(caseDTO.getTempFlag())) {
			this.commonService.saveAuditCasePoint(caseDTO.getCaseCode(),
					transferJson, userName);
		}
	}
}
